﻿using System.Collections.ObjectModel;
using System.Windows;
using algorithms;
using snat.model;

namespace gui {

    /// <summary>
    /// Encapsulates initialisation details
    /// </summary>
    public sealed class Initialise {
        private static Initialise instance;
        public static Initialise Instance {
            get {
                if (instance == null) instance = new Initialise();
                return instance;
            }
        }

        public static event guiLoadingBoxStatusUpdate LoadingBoxStatusUpdate;
        public static event guiAlgorithmsListBuiltEvent AlgorithmsListBuiltEvent;

        public void InitNetworkModel(INodeFactory factory, ObservableCollection<AlgorithmItem> list) {

            // Initialise Network Model with NodeFactory
            if (LoadingBoxStatusUpdate != null) LoadingBoxStatusUpdate("Building Network Model. Initialising nodes.");
            NetworkModel.Instance.InitNodes(factory);
 
            bool success;
            ObservableCollection<AlgorithmItem> filterList = new ObservableCollection<AlgorithmItem>();
            if (LoadingBoxStatusUpdate != null) LoadingBoxStatusUpdate("Building Network Model. Registering algorithms.");
            foreach (AlgorithmItem a in list) {
                success = false;

                // Register Algorithm and Populate NetworkTab Filter List
                if (a.Selected == true) {
                    success = AlgorithmSet.Instance.TryRegister(a.Name);
                    if (success) {
                        filterList.Add(a);  // Add the algorithm to the filterList to be sent to NetworkTab
                    } else {
                        MessageBox.Show("Warning : Could not register algorithm " + a.Name, "Warning", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }

            // Communicate with GUI
            if (AlgorithmsListBuiltEvent != null) AlgorithmsListBuiltEvent(filterList);
            if (LoadingBoxStatusUpdate != null) LoadingBoxStatusUpdate("Building Network Model. Loading initial connections and algorithms.");

            // Initialise Network Model
            NetworkModel.Instance.Init();

            // Close box
            if (LoadingBoxStatusUpdate != null) LoadingBoxStatusUpdate("Close");

        }



    }
}
